<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js"></script>

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4338ca',
                        secondary: '#10b981',
                        board: '#d4a86a',
                        dark: '#374151',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .board-grid {
                background-size: calc(100% - 2px) calc(100% - 2px);
                background-position: 1px 1px;
            }
            .piece-shadow {
                filter: drop-shadow(0 4px 3px rgb(0 0 0 / 0.07)) drop-shadow(0 2px 2px rgb(0 0 0 / 0.06));
            }
            .difficulty-btn.active {
                @apply bg-primary text-white;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen flex flex-col">
    <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-2xl font-bold text-primary flex items-center">
                <i class="fa fa-gamepad mr-2"></i>五子棋游戏
            </h1>
            <div class="flex space-x-2">
                <button id="new-game-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center">
                    <i class="fa fa-refresh mr-2"></i>新游戏
                </button>
            </div>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8 flex flex-col md:flex-row gap-8">
        <!-- 游戏状态 -->
        <div class="w-full md:w-1/4 bg-white rounded-xl shadow-md p-6">
            <h2 class="text-xl font-bold text-dark mb-4 flex items-center">
                <i class="fa fa-info-circle mr-2"></i>游戏状态
            </h2>

            <div id="game-status" class="mb-6">
                <p class="text-slate-600 mb-2">等待游戏开始...</p>
            </div>

            <div id="player-info" class="mb-6 hidden">
                <h3 class="font-semibold text-slate-700 mb-2">玩家信息</h3>
                <div class="flex items-center space-x-3 mb-2">
                    <div id="player1" class="w-8 h-8 rounded-full bg-black flex items-center justify-center text-white">X</div>
                    <span id="player1-status" class="text-sm text-slate-600">玩家1</span>
                </div>
                <div class="flex items-center space-x-3">
                    <div id="player2" class="w-8 h-8 rounded-full bg-white border-2 border-slate-700 flex items-center justify-center text-slate-700">O</div>
                    <span id="player2-status" class="text-sm text-slate-600">玩家2</span>
                </div>
            </div>

            <div id="game-mode-select" class="mb-6">
                <h3 class="font-semibold text-slate-700 mb-3">选择游戏模式</h3>
                <div class="space-y-3">
                    <button id="pvp-mode-btn" class="w-full bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center justify-center">
                        <i class="fa fa-users mr-2"></i>玩家对战
                    </button>
                    <button id="pve-mode-btn" class="w-full bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center justify-center">
                        <i class="fa fa-robot mr-2"></i>人机对战
                    </button>
                </div>
            </div>

            <div id="difficulty-select" class="mb-6 hidden">
                <h3 class="font-semibold text-slate-700 mb-3">选择难度</h3>
                <div class="grid grid-cols-3 gap-2">
                    <button id="easy-btn" class="difficulty-btn bg-slate-200 hover:bg-slate-300 text-slate-700 px-3 py-2 rounded-lg transition-all text-center">简单</button>
                    <button id="medium-btn" class="difficulty-btn bg-slate-200 hover:bg-slate-300 text-slate-700 px-3 py-2 rounded-lg transition-all text-center active">中等</button>
                    <button id="hard-btn" class="difficulty-btn bg-slate-200 hover:bg-slate-300 text-slate-700 px-3 py-2 rounded-lg transition-all text-center">困难</button>
                </div>
            </div>

            <div id="game-controls" class="hidden">
                <button id="join-random-btn" class="w-full bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg transition-all mb-3 flex items-center justify-center">
                    <i class="fa fa-sign-in mr-2"></i>加入随机游戏
                </button>
                <div class="flex space-x-2">
                    <button id="create-game-btn" class="flex-1 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center justify-center">
                        <i class="fa fa-plus mr-2"></i>创建游戏
                    </button>
                    <input type="number" id="game-id-input" class="flex-1 border border-slate-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="游戏ID">
                    <button id="join-game-btn" class="flex-1 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center justify-center">
                        <i class="fa fa-arrow-right mr-2"></i>加入
                    </button>
                </div>
            </div>

            <button id="start-ai-game-btn" class="w-full bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all mt-4 hidden">
                <i class="fa fa-play mr-2"></i>开始人机对战
            </button>
        </div>

        <!-- 游戏棋盘 -->
        <div class="w-full md:w-2/4 flex flex-col items-center">
            <div class="relative w-full max-w-lg aspect-square">
                <div id="board" class="w-full h-full bg-board rounded-lg shadow-lg relative board-grid" style="background-image: linear-gradient(to right, rgba(0,0,0,0.7) 1px, transparent 1px), linear-gradient(to bottom, rgba(0,0,0,0.7) 1px, transparent 1px); background-size: calc(100% / 14) calc(100% / 14);">
                    <!-- 棋子将通过JavaScript动态添加 -->
                </div>

                <!-- 加载中动画 -->
                <div id="loading-overlay" class="absolute inset-0 bg-black/20 rounded-lg flex items-center justify-center hidden">
                    <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-white"></div>
                </div>
            </div>

            <div id="game-result" class="mt-6 p-4 rounded-lg bg-white shadow-md hidden">
                <p id="result-text" class="text-center text-xl font-bold"></p>
            </div>
        </div>

        <!-- 游戏历史 -->
        <div class="w-full md:w-1/4 bg-white rounded-xl shadow-md p-6">
            <h2 class="text-xl font-bold text-dark mb-4 flex items-center">
                <i class="fa fa-history mr-2"></i>游戏历史
            </h2>

            <div id="move-history" class="max-h-[400px] overflow-y-auto space-y-2">
                <p class="text-slate-500 italic text-sm">游戏开始后显示历史记录</p>
            </div>
        </div>
    </main>

    <footer class="bg-white py-4 border-t border-slate-200">
        <div class="container mx-auto px-4 text-center text-slate-500 text-sm">
            <p>© 2025 五子棋游戏 | 使用 Flask 和 Socket.IO 构建</p>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 连接到WebSocket服务器
            const socket = io.connect('http://' + document.domain + ':' + location.port);

            // DOM元素
            const board = document.getElementById('board');
            const gameStatus = document.getElementById('game-status');
            const playerInfo = document.getElementById('player-info');
            const player1Status = document.getElementById('player1-status');
            const player2Status = document.getElementById('player2-status');
            const gameModeSelect = document.getElementById('game-mode-select');
            const difficultySelect = document.getElementById('difficulty-select');
            const pvpModeBtn = document.getElementById('pvp-mode-btn');
            const pveModeBtn = document.getElementById('pve-mode-btn');
            const easyBtn = document.getElementById('easy-btn');
            const mediumBtn = document.getElementById('medium-btn');
            const hardBtn = document.getElementById('hard-btn');
            const startAiGameBtn = document.getElementById('start-ai-game-btn');
            const gameControls = document.getElementById('game-controls');
            const createGameBtn = document.getElementById('create-game-btn');
            const joinGameBtn = document.getElementById('join-game-btn');
            const joinRandomBtn = document.getElementById('join-random-btn');
            const gameIdInput = document.getElementById('game-id-input');
            const moveHistory = document.getElementById('move-history');
            const gameResult = document.getElementById('game-result');
            const resultText = document.getElementById('result-text');
            const newGameBtn = document.getElementById('new-game-btn');
            const loadingOverlay = document.getElementById('loading-overlay');

            // 游戏状态变量
            let playerNumber = null;
            let gameId = null;
            let currentPlayer = 1;
            let boardSize = 15;
            let isGameOver = false;
            let isAiGame = false;
            let aiDifficulty = 'medium';

            // 初始化棋盘
            function initializeBoard() {
                board.innerHTML = '';
                board.style.backgroundSize = `calc(100% / ${boardSize - 1}) calc(100% / ${boardSize - 1})`;

                // 创建棋盘交叉点
                for (let i = 0; i < boardSize; i++) {
                    for (let j = 0; j < boardSize; j++) {
                        const cell = document.createElement('div');
                        cell.className = 'absolute cursor-pointer hover:bg-white/20 transition-colors';
                        cell.style.width = `calc(100% / ${boardSize})`;
                        cell.style.height = `calc(100% / ${boardSize})`;
                        cell.style.left = `calc(${j} * (100% / ${boardSize}))`;
                        cell.style.top = `calc(${i} * (100% / ${boardSize}))`;
                        cell.dataset.row = i;
                        cell.dataset.col = j;

                        // 添加点击事件
                        cell.addEventListener('click', function() {
                            if (isGameOver) return;

                            const row = parseInt(this.dataset.row);
                            const col = parseInt(this.dataset.col);

                            // 检查是否是当前玩家
                            if (playerNumber === currentPlayer) {
                                // 发送移动到服务器
                                socket.emit('make_move', {
                                    game_id: gameId,
                                    player: playerNumber,
                                    row: row,
                                    col: col
                                });
                            } else {
                                showMessage('不是你的回合！', 'error');
                            }
                        });

                        board.appendChild(cell);
                    }
                }
            }

            // 显示消息
            function showMessage(message, type = 'info') {
                const messageElement = document.createElement('div');
                messageElement.className = `p-3 rounded-lg ${type === 'error' ? 'bg-red-50 text-red-800 border border-red-200' : 'bg-blue-50 text-blue-800 border border-blue-200'}`;
                messageElement.innerHTML = `<p>${message}</p>`;

                gameStatus.innerHTML = '';
                gameStatus.appendChild(messageElement);

                // 3秒后自动隐藏
                setTimeout(() => {
                    messageElement.style.opacity = '0';
                    messageElement.style.transition = 'opacity 0.5s';
                    setTimeout(() => {
                        if (gameStatus.firstChild === messageElement) {
                            gameStatus.innerHTML = '';
                        }
                    }, 500);
                }, 3000);
            }

            // 更新玩家状态
            function updatePlayerStatus() {
                if (playerNumber === 1) {
                    player1Status.innerHTML = isAiGame ? '你 <span class="text-green-500 font-semibold">(X)</span>' : '玩家1 <span class="text-green-500 font-semibold">(X)</span>';
                    player2Status.innerHTML = isAiGame ? `AI (${getDifficultyName(aiDifficulty)}) <span class="text-green-500 font-semibold">(O)</span>` : '玩家2 <span class="text-green-500 font-semibold">(O)</span>';
                } else if (playerNumber === 2) {
                    player1Status.innerHTML = '玩家1 <span class="text-green-500 font-semibold">(X)</span>';
                    player2Status.innerHTML = '你 <span class="text-green-500 font-semibold">(O)</span>';
                }

                // 更新当前玩家指示器
                if (currentPlayer === 1) {
                    player1Status.innerHTML += ' <i class="fa fa-circle text-xs ml-1"></i>';
                } else {
                    player2Status.innerHTML += ' <i class="fa fa-circle text-xs ml-1"></i>';
                }
            }

            // 获取难度名称
            function getDifficultyName(difficulty) {
                switch(difficulty) {
                    case 'easy': return '简单';
                    case 'medium': return '中等';
                    case 'hard': return '困难';
                    default: return difficulty;
                }
            }

            // 添加棋子到棋盘
            function addPiece(row, col, player) {
                const cell = board.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                if (cell) {
                    const piece = document.createElement('div');
                    piece.className = `absolute inset-0 m-auto rounded-full w-[80%] h-[80%] piece-shadow transition-all duration-300 transform scale-0`;

                    if (player === 1) {
                        piece.classList.add('bg-black');
                    } else {
                        piece.classList.add('bg-white', 'border-2', 'border-slate-700');
                    }

                    cell.appendChild(piece);

                    // 添加动画效果
                    setTimeout(() => {
                        piece.classList.remove('scale-0');
                        piece.classList.add('scale-100');
                    }, 50);

                    // 添加到历史记录
                    const moveNumber = moveHistory.querySelectorAll('div').length + 1;
                    const moveElement = document.createElement('div');
                    moveElement.className = 'p-2 rounded-lg bg-slate-50 hover:bg-slate-100 transition-colors';

                    let playerName = '';
                    if (isAiGame) {
                        playerName = player === 1 ? '你' : `AI (${getDifficultyName(aiDifficulty)})`;
                    } else {
                        playerName = player === 1 ? '玩家1' : '玩家2';
                    }

                    moveElement.innerHTML = `
                        <div class="flex justify-between items-center">
                            <span class="font-medium">${moveNumber}. ${playerName}</span>
                            <span class="text-sm text-slate-500">${String.fromCharCode(65 + col)}${row + 1}</span>
                        </div>
                    `;
                    moveHistory.appendChild(moveElement);

                    // 滚动到底部
                    moveHistory.scrollTop = moveHistory.scrollHeight;
                }
            }

            // 重置游戏
            function resetGame() {
                playerNumber = null;
                gameId = null;
                currentPlayer = 1;
                isGameOver = false;
                isAiGame = false;
                aiDifficulty = 'medium';

                gameStatus.innerHTML = '<p class="text-slate-600 mb-2">等待游戏开始...</p>';
                playerInfo.classList.add('hidden');
                gameModeSelect.classList.remove('hidden');
                difficultySelect.classList.add('hidden');
                startAiGameBtn.classList.add('hidden');
                gameControls.classList.add('hidden');
                gameResult.classList.add('hidden');
                moveHistory.innerHTML = '<p class="text-slate-500 italic text-sm">游戏开始后显示历史记录</p>';

                // 重置难度按钮状态
                easyBtn.classList.remove('active');
                mediumBtn.classList.add('active');
                hardBtn.classList.remove('active');

                initializeBoard();
            }

            // 事件监听器
            createGameBtn.addEventListener('click', function() {
                loadingOverlay.classList.remove('hidden');
                if (isAiGame) {
                    socket.emit('create_ai_game', { difficulty: aiDifficulty });
                } else {
                    socket.emit('create_game');
                }
            });

            joinGameBtn.addEventListener('click', function() {
                const id = gameIdInput.value.trim();
                if (id) {
                    loadingOverlay.classList.remove('hidden');
                    socket.emit('join_game', { game_id: parseInt(id) });
                } else {
                    showMessage('请输入游戏ID', 'error');
                }
            });

            joinRandomBtn.addEventListener('click', function() {
                loadingOverlay.classList.remove('hidden');
                socket.emit('join_game', { game_id: 0 }); // 0表示随机加入
            });

            newGameBtn.addEventListener('click', resetGame);

            pvpModeBtn.addEventListener('click', function() {
                isAiGame = false;
                gameModeSelect.classList.add('hidden');
                gameControls.classList.remove('hidden');
            });

            pveModeBtn.addEventListener('click', function() {
                isAiGame = true;
                gameModeSelect.classList.add('hidden');
                difficultySelect.classList.remove('hidden');
                startAiGameBtn.classList.remove('hidden');
            });

            easyBtn.addEventListener('click', function() {
                aiDifficulty = 'easy';
                easyBtn.classList.add('active');
                mediumBtn.classList.remove('active');
                hardBtn.classList.remove('active');
            });

            mediumBtn.addEventListener('click', function() {
                aiDifficulty = 'medium';
                easyBtn.classList.remove('active');
                mediumBtn.classList.add('active');
                hardBtn.classList.remove('active');
            });

            hardBtn.addEventListener('click', function() {
                aiDifficulty = 'hard';
                easyBtn.classList.remove('active');
                mediumBtn.classList.remove('active');
                hardBtn.classList.add('active');
            });

            startAiGameBtn.addEventListener('click', function() {
                loadingOverlay.classList.remove('hidden');
                socket.emit('create_ai_game', { difficulty: aiDifficulty });
            });

            // Socket.IO事件处理
            socket.on('connect', function() {
                showMessage('已连接到服务器，等待游戏开始...');
            });

            socket.on('disconnect', function() {
                showMessage('与服务器的连接已断开', 'error');
                gameControls.classList.add('hidden');
                gameStatus.innerHTML = '<p class="text-red-500 mb-2">与服务器的连接已断开</p>';
            });

            socket.on('game_created', function(data) {
                loadingOverlay.classList.add('hidden');
                gameId = data.game_id;

                if (data.ai_game) {
                    showMessage(`已创建与AI的游戏 (${getDifficultyName(data.difficulty)})`);
                    aiDifficulty = data.difficulty;
                } else {
                    showMessage(`游戏已创建，ID: ${gameId}。等待对手加入...`);
                }

                gameControls.classList.add('hidden');
            });

            socket.on('game_started', function(data) {
                loadingOverlay.classList.add('hidden');
                playerNumber = data.player_number;
                gameId = data.game_id || gameId;
                currentPlayer = 1;
                isGameOver = false;

                gameStatus.innerHTML = '<p class="text-slate-600 mb-2">游戏开始！</p>';
                playerInfo.classList.remove('hidden');

                if (isAiGame) {
                    gameControls.classList.add('hidden');
                    difficultySelect.classList.add('hidden');
                    startAiGameBtn.classList.add('hidden');
                } else {
                    gameControls.classList.add('hidden');
                }

                updatePlayerStatus();

                // 初始化棋盘
                initializeBoard();

                // 如果有初始棋盘状态，渲染它
                if (data.board) {
                    for (let i = 0; i < boardSize; i++) {
                        for (let j = 0; j < boardSize; j++) {
                            if (data.board[i][j] !== 0) {
                                addPiece(i, j, data.board[i][j]);
                            }
                        }
                    }
                }

                showMessage(`你是玩家 ${playerNumber === 1 ? '1 (X)' : '2 (O)'}`, 'info');
            });

            socket.on('move_made', function(data) {
                // 更新当前玩家
                currentPlayer = data.current_player;

                // 添加棋子
                addPiece(data.row, data.col, data.player);

                // 更新玩家状态
                updatePlayerStatus();

                // 显示当前状态
                gameStatus.innerHTML = `
                    <p class="text-slate-600 mb-2">${currentPlayer === playerNumber ? '你的回合' : isAiGame ? 'AI思考中...' : '对手的回合'}</p>
                `;
            });

            socket.on('game_over', function(data) {
                isGameOver = true;

                if (data.winner === 0) {
                    resultText.textContent = '游戏平局！';
                    showMessage('游戏平局！', 'info');
                } else if (data.winner === playerNumber) {
                    resultText.textContent = isAiGame ? '恭喜，你击败了AI！' : '恭喜，你赢了！';
                    showMessage(isAiGame ? '恭喜，你击败了AI！' : '恭喜，你赢了！', 'info');
                } else {
                    resultText.textContent = isAiGame ? `你输给了AI (${getDifficultyName(aiDifficulty)})！` : '你输了，再接再厉！';
                    showMessage(isAiGame ? `你输给了AI (${getDifficultyName(aiDifficulty)})！` : '你输了，再接再厉！', 'error');
                }

                gameResult.classList.remove('hidden');
            });

            socket.on('error', function(data) {
                loadingOverlay.classList.add('hidden');
                showMessage(data.message, 'error');
            });

            // 初始化棋盘
            initializeBoard();
        });
    </script>
</body>
</html>